from osgeo import gdal_array
import operator
from functools import reduce


def histogram(a, bins=list(range(0, 256))):
    fa = a.flat
    n = gdal_array.numpy.searchsorted(gdal_array.numpy.sort(fa), bins)
    hist = n[1:] - n[:-1]
    return hist


def strehch(a):
    hist = histogram(a)
    lut = []
    for b in range(0, len(hist), 256):
        step = reduce(operator.add, hist[b:b+256])/255
        n = 0
        for i in range(255):
            lut.append(n/step)
            n = n + hist[i + b]
    gdal_array.numpy.take(lut, a, out=a)
    asrc="swap_02.tif"
    return asrc

arr = gdal_array.LoadFile("TIF/FalseColor/swap.tif")
stretched = strehch(arr)
output = gdal_array.SaveArray(arr, "TIF/FalseColor/stretched.tif", format="GTiff",
                              prototype="TIF/FalseColor/swap.tif")
output = None